package com.sam.im.heiqun.uis.fragments;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.transition.Slide;
import android.util.ArrayMap;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.othershe.groupindexlib.helper.SortHelper;
import com.sam.im.heiqun.R;
import com.sam.im.heiqun.constant.Constant;
import com.sam.im.heiqun.entities.ImFriendEntivity;
import com.sam.im.heiqun.entities.ImMessage;
import com.sam.im.heiqun.entities.UserEntivity;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.uis.activities.FriendDetailActivity;
import com.sam.im.heiqun.uis.activities.SelecteLocalFriendActivity;
import com.sam.im.heiqun.uis.adapters.FriendAdpter;
import com.sam.im.heiqun.uis.widgets.sidebar.CharacterParserUtil;
import com.sam.im.heiqun.uis.widgets.sidebar.CountryComparator;
import com.sam.im.heiqun.uis.widgets.sidebar.CountrySortModel;
import com.sam.im.heiqun.uis.widgets.sidebar.GetCountryNameSort;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.sam.im.heiqun.widgets.AZSideBarView;
import com.sam.im.heiqun.widgets.SideBar;
import com.sam.im.heiqun.widgets.SlideBar;
import com.yuyh.library.uis.fragments.BaseFragment;
import com.yuyh.library.utils.DividerItemDecorationUtils;
import com.yuyh.library.utils.log.LogUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import me.zhouzhuo.zzletterssidebar.ZzLetterSideBar;

/*

 */
public class FriendFragment extends BaseFragment implements FriendAdpter.FriendListClickListener {

    private static final int REFRESH_FRIEND_LIST = 1000;

   /* @BindView(R.id.new_friends)
    LinearLayout newFriends;*/
    @BindView(R.id.list_friend)
    RecyclerView list_friend;
    @BindView(R.id.friend_dialog)
    TextView dialog;



    @BindView(R.id.go_search)
    LinearLayout go_search;
    private static boolean needRefresh = false;
    private List<ImFriendEntivity> mBFriends = new ArrayList<ImFriendEntivity>();
    private List<CountrySortModel> mFriends = new ArrayList<CountrySortModel>();
    private CountryComparator pinyinComparator;
    /**
     * 获取字符串缩写
     */
    private CharacterParserUtil characterParserUtil;
    /**
     * 获取首字母
     */
    private GetCountryNameSort countryChangeUtil;
    private FriendAdpter mAdapter;

    private String TAG = "-----";
    PGService mPgService;

    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case REFRESH_FRIEND_LIST:
                    mFriends = (List<CountrySortModel>) msg.obj;
                    Collections.sort(mFriends, pinyinComparator);//根据首字母进行排序
                    mAdapter.refresh(mFriends);





                    break;
            }
        }
    };
    private List<ImFriendEntivity> imFriendEntivities = new ArrayList<>();

    @Override
    public int getContentViewId() {
        return R.layout.fragment_friend;
    }

    @Override
    public void init(Bundle savedInstanceState) {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);//订阅
        }
        initView();
        mPgService = PGService.getInstance();
        refresh();

        initSlideBar();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (needRefresh) {
            refresh();
            setNeedRefresh(false);
        }
    }


   /* @OnClick({R.id.new_friends})
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.new_friends:
                startActivity(NewFriendsActivity.class);
                break;
        }
    }*/


    @BindView(R.id.sideBar)
    SideBar mSlideBar;


    @BindView(R.id.floating_header)
    TextView tv_hint;
    private Map<String,Integer> lettes=new HashMap<String,Integer>();

    private void initSlideBar(){










       mSlideBar.setOnTouchingLetterChangedListener(new SideBar.OnChooseLetterChangedListener() {
           @Override
           public void onChooseLetter(String s) {
               if (!tv_hint.isShown())
                   tv_hint.setVisibility(View.VISIBLE);
               tv_hint.setText(s);
               selectRecyclerView(s);
           }

           @Override
           public void onNoChooseLetter() {
               tv_hint.setVisibility(View.GONE);
           }
       });

   }


    private void selectRecyclerView(String s) {



        if (s.equals("搜") ) {
            list_friend.scrollToPosition(0);
        } else {
            if(lettes.containsKey(s)){
                list_friend.scrollToPosition(lettes.get(s));
                LinearLayoutManager mLayoutManager =
                        (LinearLayoutManager) list_friend.getLayoutManager();
                mLayoutManager.scrollToPositionWithOffset(lettes.get(s), 0);

            }
        }
    }




    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);//解除订阅
        super.onDestroy();
    }

    String userId = "";

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onEventMainThread(String event) {
        if (event.equals(Constant.BLACK_BROADCAST_ADD_GROUP_FOUND_REFRESH)) {
            refresh();
        }
        if (event.equals(Constant.BLACK_BROADCAST_FOUND_REFRESH)) {
            refresh();
        }
        if (event.equals(Constant.FRAGMENT_FRIEND_REFRESH)) {
            mAdapter.refresh(mFriends);
        }
    }

    //此处所有过来的好友信息都是不全的需要通过好友id获取网络数据然后刷新界面最后存入数据库（添加好友是用）
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onImessageThread(ImMessage imMessage) {
        if (imMessage.getFromType() == Constant.FROM_TYPE_SYS && imMessage.getMessageType() == Constant.MESSAGE_TYPR_BYE_FRIEND) {
            //被对方解除了好友关系，删除本地的好友信息
            ImFriendEntivity imFriendEntivity = ImFriendEntivity.findById(ImFriendEntivity.class, imMessage.getDestid());
            if (imFriendEntivity != null) {
                imFriendEntivity.delete();
                //刷新界面
                refresh();
            }

        }
    }
    CountrySortModel countrySortModel1;
    public void refresh() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                UserEntivity userEntivity = ToolsUtils.getUser();
                userId = "" + userEntivity.getId();

                //通过数据查询数据
                synchronized (mFriends) {
                    imFriendEntivities.clear();
                    imFriendEntivities = ImFriendEntivity.find(ImFriendEntivity.class, "currentid=? ", userId);
                    mFriends.clear();


                    for (int i = 0; i < imFriendEntivities.size(); i++) {
                        Log.i("Message", "run: ----好友列表----"+imFriendEntivities.get(i).toString());
                        //取出如果好友id是66666的好友就是黑群客服，
                        if(!userId.equals("66666")){
                            if(imFriendEntivities.get(i).getId()==66666){
                                countrySortModel1 = ToolsUtils.changeFriendEntvity(imFriendEntivities.get(i), characterParserUtil, countryChangeUtil);
                                //mFriends.add(0,countrySortModel1);
                                continue;
                            }
                        }
                        CountrySortModel countrySortModel = ToolsUtils.changeFriendEntvity(imFriendEntivities.get(i), characterParserUtil, countryChangeUtil);
                        mFriends.add(countrySortModel);
                    }

                }

                Collections.sort(mFriends, pinyinComparator);//根据首字母进行排序

                //保存每个字母下的联系人在数据中的位置
                for (int i = 0; i < mFriends.size(); i++) {
                    //mFriends.get(i).setHeadIndex(i);

                    if(!lettes.containsKey(mFriends.get(i).getSortLetters())){
                        lettes.put(mFriends.get(i).getSortLetters(),i);
                    }
                }


                LogUtils.d("保存的字母:"+lettes);

                if(!userId.equals("66666")) {
                    mFriends.add(0, countrySortModel1);//取出来以后把这个黑群客服插入到第一个。
                }










                EventBus.getDefault().post(Constant.FRAGMENT_FRIEND_REFRESH);
            }
        }).start();
    }

    private void initView() {
        pinyinComparator = new CountryComparator();
        countryChangeUtil = new GetCountryNameSort();
        characterParserUtil = new CharacterParserUtil();

        list_friend.setLayoutManager(new LinearLayoutManager(getActivity()));
        mFriends = new ArrayList<>();
        mAdapter = new FriendAdpter(getActivity(), mFriends);
        mAdapter.setItemClickListener(this);
        list_friend.setAdapter(mAdapter);
        list_friend.addItemDecoration(new DividerItemDecorationUtils(getActivity(), LinearLayoutManager.HORIZONTAL, 1, getResources().getColor(R.color.black_divider)));
    }

    @Override
    public void onAgreeNewFriendClick(View view, int position) {
        if (position>0){
            Bundle bundle = new Bundle();
            bundle.putLong("id", mFriends.get(position-1).getId());
            bundle.putInt("type", 1);
            startActivityForResult(FriendDetailActivity.class, Constant.MESSAGE_MAIN_GO_GROUP_RESULT, bundle);
        }
    }

    public static void setNeedRefresh(boolean needRefresh) {
        FriendFragment.needRefresh = needRefresh;
    }


    @OnClick({R.id.go_search})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.go_search: {//搜索好友
                startActivity(SelecteLocalFriendActivity.class);
                break;
            }
        }
    }

}
